﻿using System;
using System.IO;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace VSM
{
    public partial class DocumentProfile : System.Web.UI.Page
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (Session[Utils.AppConstants.ID_User] == null
                    || Session[Utils.AppConstants.Password] == null
                    || Session[Utils.AppConstants.ID_Dealer] == null)
                {
                    Response.Redirect("../../Login.aspx");
                }

                if (!IsPostBack)
                {
                    GeneralFunctions GF = new GeneralFunctions(Utils.AppConstants.VSM, Session[Utils.AppConstants.ID_Dealer].ToString());
                    Session["DocProfileGF"] = GF;
                    LoadData();
                    if (!Session[Utils.AppConstants.ID_Dealer].ToString().Equals(Utils.AppConstants.VSM))
                    {
                        btnUpload.Visible = btnSave.Visible = false;
                    }
                    else
                        btnUpload.Visible = btnSave.Visible = true;
                }
            }
            catch (Exception ex)
            {
                string alert = "alert('Error:" + ex.Message.Replace('\'', ' ') + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", alert, true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
                e.Row.Attributes["style"] = "cursor:pointer";
                //
                HiddenField hdnIsInvalid = (HiddenField)e.Row.FindControl("hdnIsInvalid");
                DropDownList ddlDocType = (DropDownList)e.Row.FindControl("ddlDocType");
                if (hdnIsInvalid != null && ddlDocType != null) ddlDocType.SelectedValue = hdnIsInvalid.Value;  
            }
        }

        protected void ddlDocType_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlDocType = (DropDownList)row.FindControl("ddlDocType");

                HiddenField hdnIsInvalid = (HiddenField)row.FindControl("hdnIsInvalid");
                if (hdnIsInvalid != null && !string.IsNullOrEmpty(hdnIsInvalid.Value))
                {
                    hdnIsInvalid.Value = ddlDocType.SelectedValue;
                    DataTable tblDocProfile = (DataTable)Session["DocumentProfile"];
                    Label lblNo = (Label)row.FindControl("lblNo");
                    //
                    DataRow[] rowUpdate = tblDocProfile.Select("No=" + lblNo.Text);
                    if (rowUpdate.Length > 0)
                    {
                        rowUpdate[0]["isinvalid"] = hdnIsInvalid.Value;
                    }

                    BindItem(tblDocProfile);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                HiddenField hdnInternalID = (HiddenField)row.FindControl("hdnInternalID");
                HiddenField hdnFileName = (HiddenField)row.FindControl("hdnFileName");
                string strURL = Server.MapPath("~/SupportDocs/Documents/" + hdnInternalID.Value + "_" + hdnFileName.Value);
                Transaction ts = new Transaction();
                DataSet dsRtn = ts.DeleteMasterFile(Utils.AppConstants.VSM, hdnInternalID.Value);
                if ((int)dsRtn.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    lblError.Text = GeneralFunctions.UrlFullEncode(dsRtn.Tables[0].Rows[0]["ErrMsg"].ToString());
                    lblError.Visible = true;
                }
                else
                {
                    lblError.Text = "Operation complete sucessful!";
                    lblError.ForeColor = System.Drawing.Color.Blue;
                    lblError.Visible = true;
                    File.Delete(strURL);
                    Response.Redirect("DocumentProfile.aspx");
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnkDownload_Click(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                HiddenField hdnInternalID = (HiddenField)row.FindControl("hdnInternalID");
                HiddenField hdnFileName = (HiddenField)row.FindControl("hdnFileName");

                string strURL = Server.MapPath("~/SupportDocs/Documents/" + hdnInternalID.Value + "_" + hdnFileName.Value);
                WebClient req = new WebClient();
                HttpResponse response = HttpContext.Current.Response;
                response.Clear();
                response.ClearContent();
                response.ClearHeaders();
                response.Buffer = true;
                response.AddHeader("Content-Disposition", "attachment;filename=\"" + hdnFileName.Value + "\"");
                byte[] data = req.DownloadData(strURL);
                response.BinaryWrite(data);
                response.End();
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            DataTable tblDocProfile = (DataTable)Session["DocumentProfile"];
            this.grvItem.PageIndex = e.NewPageIndex;
            BindItem(tblDocProfile);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tb"></param>
        private void BindItem(DataTable tblDocProfile)
        {
            Session["DocumentProfile"] = tblDocProfile;
            this.grvItem.DataSource = tblDocProfile;
            this.grvItem.DataBind();
        }

        private void LoadData()
        {
            GeneralFunctions GF = (GeneralFunctions)Session["DocProfileGF"];
            string sqlCommand = string.Empty;
            if (Session[Utils.AppConstants.ID_Dealer].ToString().Equals(Utils.AppConstants.VSM))
            {
                sqlCommand = "select ROW_NUMBER() Over(Order By internal_id) No, internal_id, title, convert(varchar(10), publish_date, 103) AS publish_date, "
                    + " (case when convert(varchar(10), valid_date, 112) = 99991231 then '' else convert(varchar(10), valid_date, 103) end) AS valid_date, "
                    + " (case when document_type = 0 then 'Policy' else case when document_type = 1 then 'Training' else case when document_type = 2 then 'Dealers Standard' else case when document_type = 3 then 'MKT material' else 'Others' end end end end) AS document_type, "
                    + " dept, file_name, file_type, file_date, file_by, ispublic, ";
                sqlCommand += " (case when (convert(varchar(8), isNull(publish_date, cast('01/01/1900' as date)), 112) <= convert(varchar(8),getdate(), 112)) and ( convert(varchar(8), isNull(valid_date, cast('12/31/9998' as date) ), 112) >= convert(varchar(8),getdate(), 112) ) and (isNull(isinvalid, 0) = 0) then 0 else 1 end) as isinvalid  ";
                sqlCommand += "from tbl_masterfile where ( Dept = 'ALL' or Dept = '" + Session[Utils.AppConstants.U_Department].ToString() + "' or '' = '" + Session[Utils.AppConstants.U_Department].ToString() + "') ";
            }
            else
            {
                sqlCommand = " select ROW_NUMBER() Over(Order By internal_id) No, internal_id, title, convert(varchar(10), publish_date, 103) AS publish_date, "
                    + " (case when convert(varchar(10), valid_date, 112) = 99991231 then '' else convert(varchar(10), valid_date, 103) end) AS valid_date, "
                    + " (case when document_type = 0 then 'Policy' else case when document_type = 1 then 'Training' else case when document_type = 2 then 'Dealers Standard' else case when document_type = 3 then 'MKT material' else 'Others' end end end end) AS document_type, "
                    + " dept, file_name, file_type, file_date, file_by, ispublic, ";
                sqlCommand += " (case when (convert(varchar(8), isNull(publish_date, cast('01/01/1900' as date)), 112) <= convert(varchar(8),getdate(), 112)) and ( convert(varchar(8), isNull(valid_date, cast('12/31/9998' as date) ), 112) < convert(varchar(8),getdate(), 112) ) and (isNull(isinvalid, 0) = 0) then 0 else 1 end) as isinvalid  ";
                sqlCommand += " from tbl_masterfile where ( Dept = 'ALL' or Dept = '" + Session[Utils.AppConstants.U_Department].ToString() + "' or '' = '" + Session[Utils.AppConstants.U_Department].ToString() + "') and ispublic = 1 ";
            }
            
            DataTable dtDocProfile = GF.GetMasterListBySqlCommand(Utils.AppConstants.VSM, sqlCommand);

            BindItem(dtDocProfile);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoadComplete(EventArgs e)
        {
            try
            {
                base.OnLoadComplete(e);
                if (this.Request["__EVENTARGUMENT"] != null && this.Request["__EVENTARGUMENT"].ToString() != "")
                {
                    switch (this.Request["__EVENTARGUMENT"].ToString())
                    {
                        case "UploadFile":
                            Response.Redirect("DocumentProfile.aspx");
                            break;

                        default:
                            break;
                    }
                    this.lblError.Visible = false;  
                }
            }
            catch (Exception ex)
            {
                this.lblError.Visible = true;
                this.lblError.Text = ex.Message;
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {   // Update information file to Database
                DataTable tblDocProfile = (DataTable)Session["DocumentProfile"];
                Transaction ts = new Transaction();
                DataSet dsRtn = ts.CreateMasterFile(Utils.AppConstants.VSM, tblDocProfile, true);
                if ((int)dsRtn.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    lblError.Text = GeneralFunctions.UrlFullEncode(dsRtn.Tables[0].Rows[0]["ErrMsg"].ToString());
                    lblError.Visible = true;
                }
                else
                {
                    lblError.Text = "Operation complete sucessful!";
                    lblError.ForeColor = System.Drawing.Color.Blue;
                    lblError.Visible = true;
                }
            }
            catch (Exception ex)
            {
                lblError.Text = ex.ToString();
                lblError.Visible = true;
            }
        }

        protected void grvItem_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (!Session[Utils.AppConstants.ID_Dealer].ToString().Equals(Utils.AppConstants.VSM)) grvItem.Columns[0].Visible = false;
            //if (e.Row.RowType == DataControlRowType.DataRow)
            //{
            //    GridViewRow myRow = e.Row;
            //    if (!Session[Utils.AppConstants.ID_Dealer].ToString().Equals(Utils.AppConstants.VSM))
            //    { 
                
            //    }
                
            //}
        }

    }
}